package group.rober.jeki.controller.admin;

import group.rober.jeki.entity.Article;
import group.rober.jeki.exception.JekiException;
import group.rober.jeki.service.ArticleService;
import group.rober.jeki.service.CommentService;
import group.rober.runtime.kit.DateKit;
import group.rober.runtime.kit.HtmlKit;
import group.rober.runtime.kit.StringKit;
import group.rober.search.service.SearchService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Api(description = "全文索引")
@RestController
@RequestMapping("/admin")
public class AdminSearchController {
    @Autowired
    ArticleService articleService;
    @Autowired
    CommentService commentService;
    @Autowired
    SearchService searchService;

    @ApiOperation("构建文章全文索引")
    @RequestMapping(path = "/search/build-article-index",method = {RequestMethod.POST,RequestMethod.GET})
    public void buildSearchIndex(){
        try {
            searchService.deleteAllDocument();
        } catch (IOException e) {
            throw new JekiException("清除所有索引出错",e);
        }
        List<Article> articleList = articleService.getAllArticleList();
        List<Document> articleDocuments = new ArrayList<Document>();
        for(Article article : articleList){
            Document document = new Document();
            document.add(new StringField("type", "article", Field.Store.YES));
            document.add(new StringField("id", article.getId(), Field.Store.YES));

            if(StringKit.isNotBlank(article.getTitle())){
                document.add(new TextField("title", article.getTitle(), Field.Store.YES));
            }
            if(StringKit.isNotBlank(article.getSummary())){
                document.add(new TextField("summary", article.getSummary(), Field.Store.YES));
            }
            String contentText = HtmlKit.filterHtml(article.getContent());
            if(StringKit.isNotBlank(contentText)){
                document.add(new TextField("content", contentText, Field.Store.YES));
            }
            if(article.getUpdatedTime() != null){
                document.add(new TextField("updatedTime", DateKit.format(article.getUpdatedTime()), Field.Store.YES));
            }
            document.add(new StringField("viewCount", ""+article.getViewCount(), Field.Store.YES));

            articleDocuments.add(document);
        }
        try {
            searchService.addDocuments(articleDocuments);
        } catch (IOException e) {
            throw new JekiException("构建全文索引出错");
        }
    }
}
